# encoding:utf-8
#qpy:console

import my_importer
my_importer.myImport("myTools")
my_importer.myImport("LianTong")
import LianTong
from myTools import *
	
#模板完整存储在gitee上
lianTong =[
    {    	
    	    "mobile": "手机号码",
    	    "password" : "密码",
    	    "appId" : "",
    	    "cookie": "",
    	    "token_online": "",
    	    "time" : "今天签到随机时间",
    	    "flow" : {
    	    	    "use" : "国内流量使用量",
    	    	    "remain" : "国内流量剩余量",
    	    	    "mlUse" : "免流使用量"
    	    	},
    	    	"flowDict" : {},
    	    	"state" : {
    	    	    "qianDao" : "签到状态",
    	    	    "riBao" : "日包激活状态"
    	    	}
    	}     
]

def init():
    #初始化我的工具 
    #初始化
    global session
    session = requests.session()
    global fileName
    fileName = "lianTong/lianTong.json"
    global lianTong
    lianTong = getFile(fileName)
#显示使用情况
def show(flowDict,myList):
    upState = False
    for i in range(len(myList)):
        resourceType = myList[i].get("resourceType")
        #不显示语音和短信
        if resourceType == "02" or resourceType == "04":
            continue            
        feePolicyId = myList[i]['feePolicyId']
        if flowDict.get(feePolicyId) == None:                
            upState = True
            flowDict[feePolicyId] = {
	                'feePolicyId' : feePolicyId,
	                'feePolicyName' : myList[i]['feePolicyName'],
	                'use' : myList[i]['use'],
	                'msg' : "",
	                'add' : "0",
	                'total' : myList[i].get('total')                        	
	                }
                          	
        else:
            add1 = float(myList[i]['use']) - float(flowDict[feePolicyId]['use'])
            add1 = round(add1,2)
            if add1 > 0.1:
                if flowDict[feePolicyId]['msg'] != "":
                    flowDict[feePolicyId]['msg'] += "\n"    
                time1 = getTime()[-9:]
                flowDict[feePolicyId]['msg'] += f"    +{add1}  {flowDict[feePolicyId]['use']}  {time1}"
                flowDict[feePolicyId]['use'] = myList[i]['use']
                flowDict[feePolicyId]['add'] = round(float(flowDict[feePolicyId]['add']) + add1,2)
                upState = True
            print(f"\n名称:{myList[i]['feePolicyName']}")
            if myList[i].get('total') != None:
                if float(myList[i].get('total')) != 0:
                    percentage = float(myList[i]['use'])/float(myList[i].get('total'))
                    percentage = round(percentage*100,2)
                else:
                    percentage = 100
                print(f"使用:{myList[i]['use']}/ {myList[i].get('remain')}/ {myList[i].get('total')}/ {percentage}%")
            else:
                print(f"使用:{myList[i]['use']}")
            if flowDict[feePolicyId]['msg'] != "":
                print(flowDict[feePolicyId]['msg'])
                print(f"     {flowDict[feePolicyId]['add']}") 
    return upState
                       
def main():
    
    init()
    #是否更新gitee上的数据
    upState = False
    #今天凌晨时间和今月1号时间
    day_time = float(time.mktime(datetime.date.today().timetuple()))
    day1hao = float(time.mktime(datetime.date.today().replace(day=1).timetuple()))
    #现在时间和本月用天数   
    today=datetime.datetime.today()
    month=calendar.monthrange(today.year, today.month)[1]
    #本月剩余天数
    syts = month - (day_time - day1hao)/(24*3600) + 1
    
    for index in range(len(lianTong)):
        lt =   LianTong.LianTong(lianTong[index])
        try:
            state = lt.login()
            #0代表登陆失败1代表账户密码登录2代表token登录
            if  state == 0:
                title = "登录失效\n"
                desp = lt.mobile + getTime()
                push(title + desp)
                print(title + desp)
            else:
                test(lt)
                #账户密码登录则更新数据
                if state == 1:
                    print(state)
                    upState = True
                msg = ""                
                if time.time() > getTime(lianTong[index]["time"]) and lt.state["qianDao"] == False:
                    msg += "\n\n签到:" + lt.qianDao()
                    msg += "\n\n抽奖:" + lt.chouJiang()
                    #msg += "\n\n七日:" + lt.qiRiLLB()
                    if msg.find("签到成功") > -1:
                        lianTong[index]["state"]["qianDao"] = True
                        upState = True
                        push(msg)
                
                data= lt.getUse()
                (use,remain,rbuse,mlUse,state,myList) = data
                
                add = use - float(lianTong[index]["flow"]["use"])
                add = round(add,2)
                mlAdd =mlUse - float(lianTong[index]["flow"]["mlUse"])
                mlAdd = round(mlAdd,2)
                if (use + remain) > 0:
                    flowDict = lianTong[index]["flowDict"]    
                    if show(flowDict,myList) == True:            
                        upState = True
                    if add > 0 and mlAdd + 1 < add :
                        push("免流软件未开启")
                    #每天第一次更新数据     
                    if (getTime(lianTong[index]["time"]) - day_time) < 0 :
                        lianTong[index].update(lt.__dict__)
                        lianTong[index]["time"] = getTime(random.uniform(day_time+9*3600,day_time+15*3600))
                        lianTong[index]["state"]["qianDao"] = False
                        lianTong[index]["flowDict"] = {}
                        upState = True
                    
                    elif add > remain/syts:
                        if lt.state["riBao"] == False:
                            lianTong[index]["flow"]["use"] = use
                            upState = True
                            if lt.ktribao() == True:
                                text = f"{lt.mobile}已激活日包。\n{getTime()}\n使用:{add}"
                                print(text) 
                                push(text)
                            
                print(f"\nuse:{use}\nadd:{add}\nremain:{remain}\nrbuse:{rbuse}\nmlAdd:{mlAdd}\nstate:{state}")
                
        except Exception as e:
            print(str(e))
    if upState == True:
        print("gitee数据更新")
        myPrint(lianTong)
        update(fileName,lianTong)

def test(lt):
    a = 5
     
if __name__ == "__main__":   
    main()    
    
def main_handler(event, context):
    main()  